#include "deluserdb.h"
#include "pg_common.h"

int main(int argc, char **argv) {

   char *user;
   char sql[512];
   CONNECTION_DB conn;
   PGresult *result;
   int c, user_id, force=0;

   if(getuid() != 0) {
      printf("Somente o root pode executar esse comando\n");
      exit(0);
   }

   if(argc < 2) {
      print_help();
      exit(0);
   }

   while ( (c=getopt (argc, argv, "fhr")) != -1 ) {

      switch (c) {

         case 'h':
           print_help();
      exit(0);
         break;

         case 'r':
            printf("-r a implementar (pendente)\n");
         break;

         case 'f':
            force=1;
         break;

         case '?':
         break;

      }

   }

   if(optind < argc) {
                   user = strdup(argv[optind++]);
   } else {
      printf("\n     >> Usuario nao especificado << \n\n");
      print_help();
      exit(0);
   }

   conn = init_db(DB_ARQ_CONF);
   if( PQstatus(conn->pgconn) != CONNECTION_OK ) {
      printf("Falha na conexao\n");
      exit(0);
   }

   sprintf(sql, "SELECT * FROM user_sys WHERE login='%s'", user);
   result = PQexec(conn->pgconn, sql);
   if(PQntuples(result)==0) {
      printf("Usuario nao existe\n");
      free_db(conn);
      exit(0);
   } else {
      user_id = atoi(PQgetvalue(result,0,0));
   }



   if(force==0) {

      printf("Realmente deseja remover o usuario '%s' ? [s/n] ", user);
      while( (c=getchar()) != 's' && c != 'n' ) {
         printf("Realmente deseja remover o usuario '%s' ? [s/n] ", user);
         getchar();
      }
      if(c=='n') exit(0);

   }

   sprintf(sql, "DELETE FROM user_sys WHERE login='%s'", user);
   PQexec(conn->pgconn, sql);

   sprintf(sql, "DELETE FROM user_shadow WHERE user_id='%d'", user_id);
   PQexec(conn->pgconn, sql);

   printf("Usuario removido '%s'\n", user);

   free_db(conn);
   return 0;

}

void print_help() {

   printf("Uso correto: deluserdb [options] LOGIN\n\n");
   printf("Opcoes:\n");
   printf("  -r      Home do usuario (padrao: /home/bcc/LOGIN)\n");
   printf("  -h      Mostra essa ajuda\n");
   printf("\nSECURE DB USERS SYSTEM MANAGEMENT\n");

}
